package com.lw.extraceim.ui.fragments;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.lw.extraceim.R;
import com.lw.extraceim.app.AppConstants;
import com.lw.extraceim.app.ExtraceApplication;
import com.lw.extraceim.loader.ExpressSheetLoader;
import com.lw.extraceim.model.ExpressSheet;
import com.lw.extraceim.net.HttpResponseParam;
import com.lw.extraceim.net.ResponseCode;
import com.lw.extraceim.net.callback.HttpResponseParamCallback;
import com.lw.extraceim.ui.activity.SearchActivity;
import com.lw.extraceim.ui.activity.es.ExpressSheetInfoActivity;
import com.lw.extraceim.ui.activity.es.WriteExpressSheetActivity;
import com.lw.extraceim.ui.activity.base.BaseActivity;
import com.lw.extraceim.ui.adapter.ExpressSheetAdapter;
import com.lw.extraceim.ui.fragments.base.BaseFragment;
import com.lw.extraceim.util.DialogUtil;
import com.lw.extraceim.util.JsonUtils;
import com.lw.extraceim.zxing.ExtraceCaptureActivity;

import org.json.JSONException;

import java.util.List;

import okhttp3.Call;

/*这是揽件的Fragment*/
public class CollectFragment extends BaseFragment {
    private static final String TAG = "CollectFragment";

    private ListView listView;//展示揽件的listview
    private ImageButton imageButtonAddpackge;//添加揽件的imageButton
    private List<ExpressSheet> expressSheets; //当前页面的快件列表

    public CollectFragment(Context mContext, ExtraceApplication application) {
        super(mContext, application);
    }

    //初始化布局
    @Override
    public View initView() {
        View view;
        view = LayoutInflater.from(mContext).inflate(R.layout.layout_collect_fragment, null);
        listView = view.findViewById(R.id.listview_collect);
        imageButtonAddpackge = view.findViewById(R.id.imagebutton_add_packge);
        return view;
    }

    // 初始化数据
    @Override
    public void initData() {
        Log.d(TAG, "initData: " + application.getUserInfo());
        loadEsList(application.getUserInfo().getuId());
    }

    public void initEvent() {
        imageButtonAddpackge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((BaseActivity) getActivity()).startQRScan(getActivity(), ExtraceCaptureActivity.class, "扫描二维码", ExtraceCaptureActivity.SCAN_NEW_ES);
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ExpressSheet es = expressSheets.get(position);
                ExpressSheetInfoActivity.actionStart(getContext(), es);
            }
        });
    }

    /**
     * 查询当前用户揽收的快件
     *
     * @param userId
     */
    public void loadEsList(int userId) {
        final ExpressSheetLoader expressSheetLoader = new ExpressSheetLoader(getContext());
        expressSheetLoader.getEsList(userId, ExpressSheet.STATUS.STATUS_RECEIVED, new HttpResponseParamCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                alert("网络错误" + e.getMessage());
                Log.d(TAG, "onError: 网络错误" + e.getMessage());
            }

            @Override
            public void onResponse(HttpResponseParam response, int id) {
                Log.d(TAG, "onResponse: " + response.reseponseJson);
                if (response.code.getCode() == ResponseCode.SUCESS) {
                    try {
                        expressSheets = JsonUtils.fromJson(response.reseponseJson.getJSONArray("esList").toString(), new TypeToken<List<ExpressSheet>>() {
                        });
                        for (ExpressSheet expressSheet : expressSheets) {
                            expressSheet.onLoad();
                        }
                        listView.setAdapter(new ExpressSheetAdapter(expressSheets, getContext()));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Override
    public void refreshUI() {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ExtraceCaptureActivity.SCAN_NEW_ES: {
                IntentResult scanResult = IntentIntegrator.parseActivityResult(IntentIntegrator.REQUEST_CODE, resultCode, data);
                if (scanResult != null) {
                    esIsExist(scanResult.getContents().toString());
                } else {
                    toast("扫描错误");
                }
                break;
            }
        }

    }

    /**
     * 检查快件信息是否存在
     * 如果不存在就跳转到快件编辑界面
     *
     * @param esId
     */
    public void esIsExist(final String esId) {
        ExpressSheetLoader esLoader = new ExpressSheetLoader(getContext());
        esLoader.get(esId, new HttpResponseParamCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                alert("网络错误" + e.getMessage());
            }

            @Override
            public void onResponse(HttpResponseParam response, int id) {
                if (response.code.getCode() == ResponseCode.SUCESS) {
                    DialogUtil.alert(getContext(),"快件信息已存在!");
                } else if (response.code.getCode() == ResponseCode.FIAL) {
                    ExpressSheet es = new ExpressSheet();
                    es.setId(esId);
                    WriteExpressSheetActivity.actionStart(getActivity(), AppConstants.ACTION_NEW, es);
                } else {
                    alert(response.code.getMessage());
                }
            }
        });

    }

}
